package com.gitee.cirnochat.chat.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.gitee.cirnochat.chat.model.vo.req.*;
import com.gitee.cirnochat.chat.model.vo.resp.SignalMessageResponse;
import com.gitee.cirnochat.chat.service.ChatService;
import com.gitee.cirnochat.common.model.vo.resp.Result;
import com.gitee.cirnochat.common.utils.RequestUtils;
import com.gitee.cirnochat.websocket.model.vo.resp.WebSocketMessageResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;

import static com.gitee.cirnochat.common.constant.WebSocketConstant.*;

@Controller
@RequiredArgsConstructor
@Slf4j
public class ChatController {
    private final ChatService chatService;


    /**
     * 处理聊天消息，将聊天消息转发到MQ进行处理
     * @param principal 当前用户
     * @return 返回结果 该返回值会发送到与之订阅的用户
     */
    @MessageMapping(CHAT_SEND_CHANNEL) // 处理客户端发送到 /app/chat 的消息
    @SendToUser(value = CHAT_SUBSCRIBE_CHANNEL, broadcast = false) // 客户端接收消息 订阅地址 /user/topic/chat
    public WebSocketMessageResponse sendChatMessage(@Payload ChatMessageSendRequest req, Principal principal) throws JsonProcessingException {
        return chatService.sendChatMessage(req,principal);
    }


    /**
     * 撤回聊天消息
     * @param revokeRequest 撤回请求
     * @param request HttpServletRequest 用于获取用户ID
     * @return 成功结果
     */
    @DeleteMapping("/chat/revoke")
    @ResponseBody
    public Result<Void> revokeMessage(@Valid @RequestBody ChatMessageRevokeRequest revokeRequest, HttpServletRequest request) {
        Long userId = RequestUtils.getUserId(request);
        chatService.revokeMessage(revokeRequest, userId);
        return Result.success();
    }


    /**
     * 处理聊天转发消息，将批量聊天消息转发到MQ进行处理
     * @param request 转发消息
     * @param principal 当前用户
     * @return 返回结果 该返回值会发送到与之订阅的用户
     */
    @MessageMapping(FORWARD_SEND_CHANNEL) // 处理客户端发送到 /app/forward 的消息
    @SendToUser(value = CHAT_SUBSCRIBE_CHANNEL, broadcast = false) // 客户端接收消息 订阅地址 /user/topic/chat
    public void forwardChatMessage(@Payload ChatMessageForwardRequest request, Principal principal) throws JsonProcessingException {
        chatService.sendBatchChatMessage(request,principal);
    }

    /**
     * 刷新用户打字状态
     */
    @MessageMapping(SESSION_STATUS_SEND_CHANNEL)
    public void heartbeat(@Payload ChatSessionStatusMessageRequest heartbeatMessage, Principal principal) {
        chatService.sendChatSessionStatus(heartbeatMessage, principal);
    }

    /**
     * 客户端发送信令消息
     */
    @MessageMapping(WEBRTC_SEND_CHANNEL)
    @SendToUser(value = WEBRTC_SUBSCRIBE_CHANNEL, broadcast = false) // 客户端接收消息 订阅地址 /user/topic/webrtc/notice
    public SignalMessageResponse handleSignal(@Payload SignalMessageRequest message, Principal principal) {
       return chatService.handleSignalMessage(message, Long.parseLong(principal.getName()));
    }


    @MessageMapping("/test")
    @SendToUser(value = CHAT_SUBSCRIBE_CHANNEL, broadcast = false) // 客户端接收消息 订阅地址 /user/topic/chat
    public String test(String message, Principal principal) {
        System.out.println("Received test message: " + message + ", from user: " + principal.getName());
        if (true) {
            throw new RuntimeException("测试异常");
        }
        return "测试消息: " + message + ", 用户: " + principal.getName();
    }


}
